using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class SpellsPerDayListCreator: MonoBehaviour {
	
	public GameObject[] InputListsByLevel;
	
	public Dictionary<int, Dictionary<int, UILabel>> inputDic;
	
	public SpellsTable spellsTable;
	
	public GameObject acceptButton;
	
	// Use this for initialization
	void Start () {
		if(spellsTable == null)
			spellsTable = new SpellsTable();
		
		inputDic = new Dictionary<int, Dictionary<int, UILabel>>();
		int c = 1;
		foreach(GameObject g in InputListsByLevel)
		{
			inputDic.Add(c, new Dictionary<int, UILabel>());
			for(int i = 0; i < g.transform.GetChildCount(); i++)
			{
				UILabel l = g.transform.GetChild(i).GetComponentInChildren<UILabel>();
				inputDic[c].Add(i,l);
				
				if(spellsTable.GetSpells(c,i) >= 0)
					inputDic[c][i].text = spellsTable.GetSpells(c,i).ToString();
				else
					inputDic[c][i].text = "-";
				
				l.callbackObject = gameObject;
				l.callbackName = "UpdateLowerFields";
				l.callbackParam = c+"_"+i;
			}
			c++;
		}
		
		UIButtonMessage message = acceptButton.AddComponent<UIButtonMessage>();
		message.target = gameObject;
		message.functionName = "Accepted";
	}
	
	void Accepted()
	{
		int c = 1;
		foreach(GameObject g in InputListsByLevel)
		{
			for(int i = 0; i < g.transform.GetChildCount(); i++)
			{
				int x;
				if(int.TryParse(inputDic[c][i].text, out x))
					spellsTable.spellTable[c][i] = x;
				else
					spellsTable.spellTable[c][i] = -1;
			}
			c++;
		}
	}
	
	void UpdateLowerFields(UILabel field)
	{
		int c = int.Parse(field.callbackParam.Split('_')[0]);
		int i = int.Parse(field.callbackParam.Split('_')[1]);
		if(c < 20)
		{
			inputDic[c+1][i].text = field.text.TrimEnd(new char[]{'_'});
			inputDic[c+1][i].hasChanged = true;
		}
	}
}
